package com.jtpay.sdk.jtpay;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.jtpay.sdk.jtpay.basepay.UnifiedPay;
import com.jtpay.sdk.jtpay.easypermissions.EasyPermissions;
import com.jtpay.sdk.jtpay.model.FlexiblePay;
import com.jtpay.sdk.jtpay.model.IntentPay;
import com.jtpay.sdk.jtpay.model.UnifiedPayHelper;
import com.jtpay.sdk.jtpay.utils.PayExceptionUtil;
import com.jtpay.sdk.jtpay.utils.PayFileUtil;
import com.jtpay.sdk.jtpay.utils.PayLogUtil;
import com.jtpay.sdk.jtpay.utils.PayToastUtil;

import java.net.URLDecoder;
import java.util.List;

import static com.jtpay.sdk.jtpay.utils.PayFileUtil.REQUEST_STORGE;

public class PayWebViewActivity extends Activity implements EasyPermissions.PermissionCallbacks, UnifiedPay.CallBack {
    private static final String URL = "url";
    private static final String QQ = "myun.tenpay";
    private static final String WEIXIN_PREFIX = "weixin";
    protected Dialog mProgressDialog;
    private WebView mWebView;
    FlexiblePay mFlexiblePay;
    private static final int REQUEST_APP_SETTING = 0x1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mWebView = new WebView(this);
        mWebView.setWebViewClient(new MyWebViewClient());
        initSettings(mWebView.getSettings());
        mWebView.addJavascriptInterface(this, "JHBack");
        mWebView.addJavascriptInterface(this, "JHMobile");
        String url = getIntent().getStringExtra(URL);
        PayLogUtil.logFifth("onCreate");
        if (!TextUtils.isEmpty(url)) {
            if (url.startsWith("weixin")) {
                PayLogUtil.logFifth("invoke");
                invoke(url);
            } else {
                mWebView.loadUrl(url);
                setContentView(mWebView);
            }
        }
    }

    private void initSettings(WebSettings settings) {
        settings.setJavaScriptEnabled(true);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        } else {
            settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mWebView.stopLoading();
        mWebView.clearHistory();
        mWebView.removeAllViews();
        mWebView.destroy();
        mWebView = null;
    }

    public static void startActivity(Activity activity, String url) {
        Intent intent = new Intent(activity, PayWebViewActivity.class);
        intent.putExtra(URL, url);
        activity.startActivity(intent);
    }


    @JavascriptInterface
    public void click(String url) {
        PayLogUtil.logFifth("click !!!!! ");
        mProgressDialog = ProgressDialog.show(this, "", "正在支付...", false, true, null);
        loadUrl(url);
    }

    @Override
    protected void onPause() {
        super.onPause();
        dismiss();
        finish();
    }

    private void loadUrl(final String url) {
        PayLogUtil.logFifth("loadUrl ");
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                PayWebView payWebView = new PayWebView(PayWebViewActivity.this, null);
                payWebView.loadUrl(url, false);
            }
        });
    }

    private void dismiss() {
        if (null != mProgressDialog && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    @JavascriptInterface
    public void invoke(String content) {
        if (null == mFlexiblePay) {
            mFlexiblePay = new FlexiblePay(content, this);
        } else {
            mFlexiblePay.setContent(content);
        }
        if (PayFileUtil.hasSDCardPermission(this)) {
            showDialog();
            UnifiedPayHelper.pay(this, mFlexiblePay);
        } else {
            PayFileUtil.requestSDCardPermission(this);
        }
        PayLogUtil.logFifth("invoke end");
    }

    private void showDialog() {
        if (null != mProgressDialog) {
            mProgressDialog.show();
        } else {
            mProgressDialog = ProgressDialog.show(this, "", "正在支付...", false, true, null);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (requestCode == REQUEST_STORGE) {
            UnifiedPayHelper.pay(this, mFlexiblePay);
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.permissionPermanentlyDenied(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            showSettingDialog();
        }
    }

    private void showSettingDialog() {
        new AlertDialog.Builder(this)
                .setTitle("请设置存储权限")
                .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startActivityForResult(new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + getPackageName())), REQUEST_APP_SETTING);
                    }
                }).show();
    }

    @Override
    public void prepareLeave() {
        dismiss();
        finish();
    }

    /**
     * resolve http and https problem with onReceivedSslError add SslErrorHandler.proceed()
     */
    private class MyWebViewClient extends WebViewClient {

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            PayLogUtil.logBase("onPageStarted url = " + url);
            if (url.contains(QQ)) {
                shareToFriendQQ(url, PayWebViewActivity.this);
                return true;
            } else if (url.startsWith(WEIXIN_PREFIX)) {
                IntentPay.intentPay(PayWebViewActivity.this, url, PayWebViewActivity.this);
                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }


    }

    private void shareToFriendQQ(String url, UnifiedPay.CallBack callBack) {
        PayLogUtil.logBase("shareToFriendQQ url = " + url);
        url = URLDecoder.decode(url);
        Intent intent = new Intent();
        ComponentName comp = new ComponentName("com.tencent.mobileqq",
                "com.tencent.mobileqq.activity.JumpActivity");
        intent.setComponent(comp);
        intent.setAction("android.intent.action.SEND");
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, url);
        try {
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            PayToastUtil.showMessage(this, "QQ can't be found!");
            PayExceptionUtil.getInstance().saveExceptionFile("PayWebViewActivity shareToFriendQQ " +
                    "Exception e = " + e.getMessage());
        } finally {
            if (null != callBack) {
                callBack.prepareLeave();
            }
        }
        PayLogUtil.logFifth("shareToFriendQQ end");
    }
}
